﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Net.Mail;
//using jmail;
using System.Net;
using System.Configuration;

namespace BaseSet.Framework
{
    /// <summary>
    /// 发送邮件 即时 建议采用 SenMailBySMTP 发送
    /// </summary>
    public class SendEmail
    {
        /// <summary>
        /// 使用CDO组件发送邮件CDO是Collaboration Data Objects的简称，它是一组高层的COM对象集合，并经历了好几个版本的演化，现在在Windows2000和Exchange2000中使用的都是CDO2.0的版本（分别为cdosys.dll和cdoex.dll）。CDOSYS构建在SMTP协议和NNTP协议之上，并且作为Windows2000 Server的组件被安装，您可以在系统目录（如c:\winnt或c:\windows）的system32子目录中找到它(cdosys.dll)。CDO组件相对于先前介绍的SmtpMail对象功能更为丰富，并提供了一些SmtpMail类所没有提供的功能，如通过需要认证的SMTP服务器发送邮件等。
        /// </summary>
        /// <param name="from">from名称</param>
        /// <param name="subject">主题</param>
        /// <param name="senderEmail">发送者email</param>
        /// <param name="emailAccount">发送者账号</param>
        /// <param name="username">用户名</param>
        /// <param name="password">用户名密码</param>
        /// <param name="smtp">邮件发送服务器</param>
        /// <param name="toEmail">收件人地址</param>
        /// <param name="content">内容</param>
        /// <returns>true:发送成功，false:发送失败</returns>
        //public static bool CDOsendMail(string from, string subject, string senderEmail, string emailAccount, string username, string password, string smtp, string toEmail, string content)
        //{
        //    try
        //    {
        //        CDO.Message oMsg = new CDO.Message();

        //        oMsg.From = from;
        //        oMsg.To = toEmail;
        //        oMsg.Subject = subject;
        //        //oMsg.HTMLBody = "<html><body><b>大家好！！</b><img src=\"http://www.micromarketing.com.cn/jmail/count.aspx?id=505&email=<收件人地址>\" width=0 height=0>link</a></body></html>";
        //        oMsg.HTMLBody = content;

        //        CDO.IConfiguration iConfg = oMsg.Configuration;
        //        ADODB.Fields oFields = iConfg.Fields as ADODB.Fields;

        //        oFields["http://schemas.microsoft.com/cdo/configuration/sendusing"].Value = 2;

        //        oFields["http://schemas.microsoft.com/cdo/configuration/sendemailaddress"]
        //            .Value = senderEmail; //sender mail

        //        oFields["http://schemas.microsoft.com/cdo/configuration/smtpaccountname"]
        //            .Value = emailAccount; //email account

        //        oFields["http://schemas.microsoft.com/cdo/configuration/sendusername"]
        //            .Value = username;
        //        oFields["http://schemas.microsoft.com/cdo/configuration/sendpassword"]
        //            .Value = password;

        //        oFields["http://schemas.microsoft.com/cdo/configuration/smtpauthenticate"]
        //            .Value = 1;

        //        //value=0 代表Anonymous验证方式（不需要验证）
        //        //value=1 代表Basic验证方式（使用basic (clear-text) authentication. 
        //        //The configuration sendusername/sendpassword or postusername/postpassword fields 
        //        //	are used to specify credentials.）
        //        //Value=2 代表NTLM验证方式（Secure Password Authentication in Microsoft Outlook Express）

        //        oFields["http://schemas.microsoft.com/cdo/configuration/languagecode"].Value = 0x0804;
        //        oFields["http://schemas.microsoft.com/cdo/configuration/smtpserver"].Value = smtp;

        //        oFields.Update();
        //        oMsg.BodyPart.Charset = "utf-8";
        //        oMsg.HTMLBodyPart.Charset = "utf-8";

        //        oMsg.Send();
        //        oMsg = null;


        //    }
        //    catch (Exception e)
        //    {

        //        return false;

        //    }

        //    return true;

        //}

        /// <summary>
        /// 通过smtp直接发送邮件
        /// </summary>
        /// <param name="fromEmail">发件人的邮箱</param>
        /// <param name="toEmail">收件人的邮箱</param>
        /// <param name="subject">主题</param>
        /// <param name="body">正文</param>
        /// <param name="smtp">邮件发送器</param>
        /// <param name="account">用户名</param>
        /// <param name="pwd">用户名密码</param>
        /// <returns>true:发送成功，false:发送失败</returns>
        public static bool SenMailBySMTP(string fromEmail, string toEmail, string subject, string body, string smtpAddress, string account, string pwd)
        {
            System.Net.Mail.MailMessage mail = new System.Net.Mail.MailMessage(fromEmail, toEmail);

            //mail.s
            mail.SubjectEncoding = Encoding.UTF8;
            mail.Subject = subject;
            mail.IsBodyHtml = true; //是否允许内容为 HTML 格式
            mail.BodyEncoding = Encoding.UTF8;
            mail.Body = body;

            //mail.Attachments.Add(new Attachment("E:\\foo.txt")); //添加一个附件

            SmtpClient smtp = new SmtpClient(smtpAddress);
            smtp.Credentials = new NetworkCredential(account, pwd); //SMTP 验证
            //smtp.DeliveryMethod = SmtpDeliveryMethod.PickupDirectoryFromIis;

            bool rr = true;

            try
            {
                smtp.Send(mail);
            }
            catch (Exception ex)
            {

                rr = false;
            }

            mail.Attachments.Dispose(); //邮件发送完毕，释放对附件的锁定


            return rr;

        }

        /// <summary>
        /// jmail发送邮件
        /// </summary>
        /// <param name="toEmail">接收者（多位用分号隔开）</param>
        /// <param name="strToName">收件人姓名</param>
        /// <param name="strTitle">邮件标题</param>
        /// <param name="strContent">邮件内容</param>
        /// <returns>true:发送成功，false:发送失败</returns>
        public static bool SendEmailByJmail(string toEmail,string strToName,string strTitle,string strContent)
        {
            string FromEmail = System.Configuration.ConfigurationManager.AppSettings["FromEmail"] + "";
            string FromName = System.Configuration.ConfigurationManager.AppSettings["FromName"] + "";
            string mailusername = System.Configuration.ConfigurationManager.AppSettings["mailusername"] + "";
            string mailpassword = System.Configuration.ConfigurationManager.AppSettings["mailpassword"] + "";
            string mailSmtpHost = System.Configuration.ConfigurationManager.AppSettings["mailSmtpHost"] + "";
            return SendMailUseJmail(toEmail, "", "", strToName, strContent, strTitle, "html", "", mailusername, FromName, mailpassword, mailSmtpHost);
        }


        #region 鉴于jmail基本不再使用，此处使用这个接口的方法已被去掉（代码保留）
        /// <summary>
        /// 使用Jmail发邮件
        /// </summary>
        /// <param name="toEmail">接收者（多位用分号隔开）</param>
        /// <param name="toCCMail">抄送（多位用分号隔开）</param>
        /// <param name="toBCCMail">密送（多位用分号隔开）</param>
        /// <param name="FromEmail">发件者</param>
        /// <param name="strToName">收件人姓名</param>
        /// <param name="strFromName">发件人姓名</param>
        /// <param name="strContent">邮件内容</param>
        /// <param name="strTitle">邮件标题</param>
        /// <param name="strContentType">邮件类别（html或者text）</param>
        /// <param name="strFiles">附件（多个用分号隔开）</param>
        /// <param name="mailusername">发件人邮件用户名</param>
        /// <param name="FromName">from名称</param>
        /// <param name="mailpassword">发件人邮箱密码</param>
        /// <param name="mailSmtpHost">邮箱服务器</param>
        /// <returns>true:发送成功，false:发送失败</returns>
        public static bool SendMailUseJmail(string toEmail, string toCCMail, string toBCCMail, string strToName, string strContent, string strTitle, string strContentType, string strFiles, string mailusername, string FromName, string mailpassword, string mailSmtpHost)
        {

            jmail.Message Jmail = new jmail.Message();
            int i = 0;
            //toBCCMail = "";
            //toCCMail = "";
            try
            {
                //Silent属性：如果设置为true,JMail不会抛出例外错误. JMail. Send( () 会根据操作结果返回true或false
                Jmail.Silent = true;
                //Jmail创建的日志，前提loging属性设置为true
                Jmail.Logging = true;
                //字符集，缺省为"US-ASCII"
                Jmail.Charset = "GB2312";
                //信件的contentype. 缺省是"text/plain"） : 字符串如果你以HTML格式发送邮件, 改为"text/html"即可。

                //Jmail.ContentType = "Multipart/Mixed";
                //添加收件人

                string[] strArryToMail;
                string[] strArryToCCMail;
                string[] strArryToBCCMail;
                // toEmail = System.Configuration.ConfigurationManager.AppSettings["toEmail"].ToString();
                if (String.IsNullOrEmpty(toEmail))
                {
                    Jmail.Close();
                    return false;
                }
                else
                {
                    strArryToMail = toEmail.Split(";".ToCharArray());
                }
                for (i = 0; i < strArryToMail.Length; i++)
                {
                    Jmail.AddRecipient(strArryToMail[i], "", "");
                }

                //Jmail.add
                //抄送         
                if (!String.IsNullOrEmpty(toCCMail))
                {
                    strArryToCCMail = toCCMail.Split(";".ToCharArray());
                    for (i = 0; i < strArryToCCMail.Length; i++)
                    {
                        Jmail.AddRecipientCC(strArryToCCMail[i], "", "");
                    }
                }

                //密送         
                if (!String.IsNullOrEmpty(toBCCMail))
                {
                    strArryToBCCMail = toBCCMail.Split(";".ToCharArray());
                    for (i = 0; i < strArryToBCCMail.Length; i++)
                    {
                        Jmail.AddRecipientBCC(strArryToBCCMail[i], "");
                    }
                }

                Jmail.From = mailusername;
                Jmail.FromName = FromName;

                //发件人邮件用户名
                Jmail.MailServerUserName = mailusername;

                //发件人邮件密码

                Jmail.MailServerPassWord = mailpassword;

                //设置邮件标题
                Jmail.Subject = strTitle;

                //邮件添加附件,(多附件的话，可以再加一条Jmail.AddAttachment( "c:\\test.jpg",true,null);)就可以搞定了。［注］：加了附件，讲把上面的Jmail.ContentType="text/html";删掉。否则会在邮件里出现乱码。

                string[] strArryFiles;
                if (!String.IsNullOrEmpty(strFiles))
                {
                    strArryFiles = strFiles.Split(";".ToCharArray());
                    for (i = 0; i < strArryFiles.Length; i++)
                    {
                        Jmail.AddAttachment(strArryFiles[i], true, null);
                    }
                }
                //邮件内容
                if (strContentType.ToLower() == "text")
                {
                    Jmail.Body = strContent;

                }
                else
                {
                    Jmail.HTMLBody = strContent;
                }
                //Jmail发送的方法
                if (Jmail.Send(mailSmtpHost, false))
                {
                    //
                    Jmail.Close();
                    return true;
                }
                else
                {
                    //
                    Jmail.Close();
                    return false;
                }

            }
            catch
            {
                Jmail.Close();
                return false;
            }
        }

        #endregion
    }
}
